package com.example.yuyin;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import com.example.db.DatabaseHelper;
import com.example.ftp.Ftp;
import com.example.ftp.FtpUploadAsyncTask;
import com.example.md5.MD5;
import com.iflytek.speech.RecognizerResult;  
import com.iflytek.speech.SpeechError;  
import com.iflytek.ui.RecognizerDialog;  
import com.iflytek.ui.RecognizerDialogListener;  

import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.Toast;

public class YuYin extends Activity {

	private EditText et;  
	private Button RecognizeBTN;  
	private static final String APPID = "appid=4f2d3a06"; 
	private final static int PROGRESSTDIALOG = 1;
	private ProgressDialog progressDialog;
	private int progress;

	private String text = "";
	private String md5request="";
	private String DIR = "";  

	private String HostName = "";  
	private String Port = "";  
	private String UserName = "";  
	private String Password = "";  

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.activity_yu_yin);

		et = (EditText)findViewById(R.id.et);
		RecognizeBTN = (Button)findViewById(R.id.bt_recognize);
		RecognizeBTN.setOnClickListener(RecognizeBtnListener);

		DatabaseHelper dbHelper = new DatabaseHelper(YuYin.this,"YuYin");
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		dbHelper.close();

		DIR="/data/data/"+this.getPackageName()+"/record";

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//		getMenuInflater().inflate(R.menu.activity_yu_yin, menu);
		menu.add(0, 1, 1, R.string.ftpsetting);
		menu.add(0, 2, 2, R.string.exit);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// TODO Auto-generated method stub
		if(item.getItemId() == 1)
		{
			Intent intent = new Intent();
			intent.setClass(YuYin.this,FtpSetting.class);
			YuYin.this.startActivity(intent);
		}
		else if (item.getItemId() == 2)
		{
//			test();
			finish();
		}
		return super.onOptionsItemSelected(item);
	}

	//语音识别
	OnClickListener RecognizeBtnListener = new OnClickListener()
	{  
		public void onClick(View v) 
		{  
			if (!GetFtpParam())
			{
				Toast.makeText(YuYin.this, "请先配置FTP参数", 500).show();
				return;
			}

			text = "";
			et.setText(text);

			//语音识别
			RecognizerDialog isrDialog = new RecognizerDialog(YuYin.this, APPID);  
			isrDialog.setEngine("sms", null, null);  
			isrDialog.setListener(recoListener);  
			isrDialog.show();  
		}  
	};  

	// 语言识别监听器，有两个方法  
	RecognizerDialogListener recoListener = new RecognizerDialogListener() {  

		public void onResults(ArrayList<RecognizerResult> results,  
				boolean isLast) {  
			// 服务器识别完成后会返回集合，我们这里就只得到最匹配的那一项  
			text += results.get(0).text;  
			System.out.println("onResults ------>"+text);  
		}  

		public void onEnd(SpeechError error) {  
			if (error == null) {  
				// 完成后就把结果显示在EditText上  
				et.setText(text);
				System.out.println("onEnd--------->"+text);  
				Process();
			}  
		}  
	};  

	@Override
	protected Dialog onCreateDialog(int id)
	{
		switch (id)
		{
		case PROGRESSTDIALOG:
			progressDialog = new ProgressDialog(this);
			progressDialog.setTitle("");//提示
			progressDialog.setMessage("");//正在上传……
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMax(10000);
			return progressDialog;
		default:
			break;
		}
		return null;
	}

	// 进度条Handler
	Handler progressHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			progress++;
			progressDialog.setProgress(progress);
			progressHandler.sendEmptyMessageDelayed(0, 100);
		}
	};

	public boolean Process() 
	{
		//以当前时间为文件名，将识别结果保存至文本。
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd__hh-mm-ss");     
		String date = sDateFormat.format(new java.util.Date());

		FileUtils fileUtils = new FileUtils();
		fileUtils.writefile(DIR, date+".txt",et.getText().toString());

		//对文本加密，并保存
		MD5 md5 = new MD5();
		md5request = md5.md5sum(DIR+File.separator+date+".txt");
		fileUtils.writefile(DIR, md5request+".txt",md5request);
		//				handler.post(updateThread);

		//显示progressbar
		YuYin.this.showDialog(PROGRESSTDIALOG);
		progress = 0;
		progressDialog.setProgress(0);
		progressHandler.sendEmptyMessage(0);

		//将识别结果文本和加密文本上传至FTP服务器。
		FtpUploadAsyncTask ftpUploadAsyncTask = new FtpUploadAsyncTask(progressDialog ,progressHandler,YuYin.this);
		ftpUploadAsyncTask.execute(HostName,Port,UserName,Password,"\\",DIR+File.separator,md5request+".txt",date+".txt");

		return true;
	}
	
	public boolean GetFtpParam() {
		DatabaseHelper dbHelper = new DatabaseHelper(YuYin.this,"YuYin");
		String StrSQL = "SELECT HostName, Port ,UserName,Password FROM FtpParam";
		Cursor cursor = dbHelper.select(StrSQL);
		while(cursor.moveToNext()){
			HostName = cursor.getString(cursor.getColumnIndex("HostName"));
			Port = cursor.getString(cursor.getColumnIndex("Port"));
			UserName = cursor.getString(cursor.getColumnIndex("UserName"));
			Password = cursor.getString(cursor.getColumnIndex("Password"));
		}
		cursor.close();
		dbHelper.close();

		if (HostName == "" || Port == "" || UserName == "")
		{
			return false;
		}
		return true;
	}
	
	private void  test()//不进行语音识别，只是测试将文本框中的数据加密和上传
	{
		if (!GetFtpParam())
		{
			Toast.makeText(YuYin.this, "请先配置FTP参数", 500).show();
			return;
		}
		Process();
	}

	Handler handler = new Handler();
	Runnable updateThread = new Runnable()
	{
		public void run()
		{
			Ftp ftp = new Ftp();
			String reString = ftp.ftpUpload(HostName,Port,UserName,Password,"\\", DIR+File.separator, md5request+".txt");

			if(reString.equals("0"))
			{
				Dialog dialog = new AlertDialog.Builder(YuYin.this).setTitle("警告").setMessage("FTP上传文件失败！"+"\n"+"请检查："+"\n"+"    1 网络连接是否正常。"+"\n"+"    2 FTP服务器是否开启。").setPositiveButton("确定", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
					}
				}).create();
				dialog.show();
			}
		}
	};
}
